package net.huashitong.ecology.controller;

import com.sirdc.modules.core.web.JsonBaseController;
import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.sys.entity.SysDept;
import com.sirdc.modules.sys.entity.SysLogin;
import com.sirdc.modules.sys.service.DeptService;
import com.sirdc.modules.sys.service.RedisService;
import com.sirdc.modules.sys.service.SysLoginService;
import com.sirdc.modules.sys.service.SysUserService;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.constant.CommonConstant;
import net.huashitong.supervision.task.entity.*;
import net.huashitong.supervision.task.filter.TaskMainFilter;
import net.huashitong.supervision.task.filter.TaskSubFilter;
import net.huashitong.supervision.task.service.*;
import net.huashitong.user.databean.LoginBean;
import net.huashitong.util.JwtUtil;
import net.huashitong.util.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

import static net.huashitong.util.JwtUtil.sign;

/**
 * 提供给生态接口
 */
@Controller
@RequestMapping("/ecoApi")
public class LoginEcoController extends JsonBaseController {
    @Lazy
    @Autowired
    private RedisService redisService;
    @Lazy
    @Autowired
    private SysLoginService sysLoginService;
    @Lazy
    @Autowired
    private SysUserService sysUserService;
    @Lazy
    @Autowired
    private TokenUtils tokenUtils;
    @Lazy
    @Autowired
    private TaskMainService taskMainService;
    @Lazy
    @Autowired
    private TaskSubService taskSubService;
    @Lazy
    @Autowired
    private TaskUnitService taskUnitService;
    @Lazy
    @Autowired
    private TaskBackNewService taskBackNewService;
    @Lazy
    @Autowired
    private TaskLogNewService taskLogNewService;
    @Lazy
    @Autowired
    private DeptService deptService;


    @Override
    protected String getView(String s) {
        return null;
    }

    /**
     * 生态接口，登录校验
     *
     * @param loginBean
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Message check(@RequestBody LoginBean loginBean) {
        String username = loginBean.getUsername();
        String password = loginBean.getPassword();
        SysLogin loginUser = sysLoginService.getUserByLoginName(username);
        if (ObjectUtils.isBlank(loginUser)) {
            return null;
        }
        String encryPass = sysUserService.getEncryPass(password, loginUser.getSaltKey());
        if (loginUser.getPassword().equals(encryPass)) {
            //登录成功 生成token
            String token = sign(loginUser.getUsername(), loginUser.getPassword());
            // 设置Toekn缓存有效时间
            redisService.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
            Map<String, String> map = new HashMap<>();
            map.put("token", token);
            return coverMessage("200", "登录成功", map);
        } else {
            //登录失败
            return coverMessage("500", "登录失败");
        }
    }

    @ResponseBody
    @RequestMapping(value = "/queryTaskInfoByTaskId", method = RequestMethod.POST)
    public Message queryTaskInfoByTaskId(@RequestBody TaskMainFilter filter) {
//        String token = filter.getToken();
//        Message resToken = checkToken(token);
//        if (ObjectUtils.isNotBlank(resToken)) {
//            return resToken;
//        }
//        TaskMain taskMain = taskMainService.getById(filter.getSysId());
//        if (ObjectUtils.isNotBlank(taskMain)) {
//            TaskSubFilter taskSubFilter = new TaskSubFilter();
//            taskSubFilter.setTaskMainId(taskMain.getSysId());
//            List<TaskSub> taskSubList = taskSubService.queryFilterNoPage(taskSubFilter);
//            for (TaskSub taskSub : taskSubList) {
//                List<TaskUnit> leadDeptList = new ArrayList<>();
//                List<TaskUnit> assistDeptList = new ArrayList<>();
//                List<TaskUnit> unitTaskList = taskUnitService.getBySubIdNoPage(taskSub.getSysId());
//                for (TaskUnit taskUnit : unitTaskList) {
//                    //封装反馈记录
//                    String taskUnitId = taskUnit.getSysId();
//                    List<TaskBackNew> taskBackNewList = taskBackNewService.getByTaskUnitId(taskUnitId);
//                    if (taskBackNewList.size() >= 0) {
//                        taskUnit.setTaskBackNewList(taskBackNewList);
//                    }
//                    if ("1".equals(taskUnit.getUnitType())) {
//                        //牵头单位
//                        leadDeptList.add(taskUnit);
//                    }
//
//                    if ("2".equals(taskUnit.getUnitType())) {
//                        //协办单位
//                        assistDeptList.add(taskUnit);
//                    }
//                }
//                taskSub.setLeadDeptList(leadDeptList);
//                taskSub.setAssistDeptList(assistDeptList);
//            }
//            taskMain.setTaskSubList(taskSubList);
//            return coverMessage("200", "查询成功！", taskMain);
//        } else {
            return coverMessage("202", "参数出错！");
//        }
    }


    /**
     * 根据主任务id获取列表
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryMainTaskByTaskId", method = RequestMethod.POST)
    public Message queryMainTaskByTaskId(@RequestBody TaskMainFilter filter) {
        String token = filter.getToken();
        Message resToken = checkToken(token);
        if (ObjectUtils.isNotBlank(resToken)) {
            return resToken;
        }
        TaskMain taskMain = taskMainService.getById(filter.getSysId());
        if (ObjectUtils.isNotBlank(taskMain)) {
            TaskSubFilter taskSubFilter = new TaskSubFilter();
            taskSubFilter.setTaskMainId(taskMain.getSysId());
            List<TaskUnit> unitTaskList = taskUnitService.getByMainIdNoPage(taskMain.getSysId());
            taskMain.setTaskUnitList(unitTaskList);
            return coverMessage("200", "查询成功！", taskMain);
        } else {
            return coverMessage("202", "参数出错！");
        }
    }


    /**
     * 查询反馈单位的反馈内容详情（多条）
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryUnitTaskDetailByTaskUnitId", method = RequestMethod.POST)
    public Message queryUnitTaskDetailByTaskUnitId(@RequestBody TaskMainFilter filter) {
        String token = filter.getToken();
        Message resToken = checkToken(token);
        if (ObjectUtils.isNotBlank(resToken)) {
            return resToken;
        }
        TaskUnit taskUnit = taskUnitService.getById(filter.getSysId());
        if (ObjectUtils.isNotBlank(taskUnit)) {
            //流程记录
            List<TaskLogNew> logNewList = taskLogNewService.getByUnitId(filter.getSysId());
            //封装反馈记录
            String taskUnitId = taskUnit.getSysId();
            List<TaskBackNew> taskBackNewList = taskBackNewService.getByTaskUnitId(taskUnitId);
            taskUnit.setTaskBackNewList(taskBackNewList);
            taskUnit.setTaskLogNewList(logNewList);
            return coverMessage("202", "查询成功！", taskUnit);
        } else {
            return coverMessage("202", "参数出错！");
        }
    }

    @ResponseBody
    @RequestMapping(value = "/getDeptList", method = RequestMethod.POST)
    public Message getDeptList(@RequestBody TaskMainFilter filter) {
        String token = filter.getToken();
        Message resToken = checkToken(token);
        if (ObjectUtils.isNotBlank(resToken)) {
            return resToken;
        }
        List<SysDept> sysDeptList = deptService.queryByDeptLevel(3);
        return coverMessage("200", "查询成功！", sysDeptList);
    }

    @ResponseBody
    @RequestMapping(value = "/createTask", method = RequestMethod.POST)
    public Message createTask(@RequestBody TaskMainFilter filter) {
        String token = filter.getToken();
        Message resToken = checkToken(token);
        if (ObjectUtils.isNotBlank(resToken)) {
            return resToken;
        }
        //生态接口默认设置参数
        filter.setUserId("ecology_user");
        filter.setCategoryId("ecology_category");
        String result = "";
        try {
            result = taskMainService.createTask(filter);
        } catch (Exception e) {
            e.printStackTrace();
            return coverMessage("500", e.getMessage());
        }
        if (!result.contains("保存成功")) {
            return coverMessage("202", result);
        } else {
            String[] mesArr = result.split("%");
            String mainTaskId = mesArr[1];
            String mainTaskName = mesArr[2];
            Map<String, String> dataMap = new HashMap<>();
            dataMap.put("mainTaskId", mainTaskId);
            dataMap.put("mainTaskName", mainTaskName);
            return coverMessage("200", "任务创建成功", dataMap);
        }
    }


    /**
     * Token 校验
     *
     * @param token
     * @return
     */
    public Message checkToken(String token) {
        String username = JwtUtil.getUsername(token);
        if (username == null) {
            return coverMessage("500", "token非法无效");
        }
        SysLogin loginUser = sysLoginService.getUserByLoginName(username);
        if (loginUser == null) {
            return coverMessage("500", "用户不存在");
        }
        // 校验token是否超时失效 & 或者账号密码是否错误
        if (!tokenUtils.jwtTokenRefresh(token, username, loginUser.getPassword())) {
            return coverMessage("500", "Token失效，请重新登录!");
        }
        return null;
    }
}
